<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Manage;
use App\Models\Stu;
use App\Models\Task;
use App\Models\Term;
use App\Models\Week;
use Illuminate\Http\Request;

class TaskUpController extends Controller
{
    public function Index(Request $request)
    {
        $task = Task::orderBy('id', 'desc')->where()->first();
        return view('admin.task.list', compact('task'));
    }

    public function data()
    {
        $data = Task::orderBy('add_time', 'ASC')->get();
        return response()->json($data)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
    }

    public function Create()
    {
        $term_id = Term::where('tag', '1')->orderBy('time_start', 'desc')->value('id');
        $title = Term::where('tag', '1')->orderBy('time_start', 'desc')->value('title');
        $week = Week::all()->where('term_id', '=', $term_id);
        return view('admin.task.create', compact('week', 'title'));
    }

    public function Update($id)
    {
        $stu = Stu::find($id);
        return view('admin.task.edit', compact('stu'));
    }

    public function Edit(Request $request)
    {
        $id = $request->input('uid');
        $term = Term::find($id);
        $title = $request->input('title');
        $bz = $request->input('bz');
        $time_start = $request->input('start');
        $time_over = $request->input('end');
        $update_time = Carbon::now()->toDateTimeString();
        $term->title = $title;
        $term->time_start = $time_start;
        $term->time_over = $time_over;
        $term->bz = $bz;
        $term->update_time = $update_time;
        $res = $term->save();
        if ($res) {
            return \redirect()->back()->with('success', '恭喜，修改成功！');
        } else {
            return \redirect()->back()->with('errors', '修改失败！');
        }
    }

    public function Add(Request $request)
    {
        //1.接受前台提交的表单数据 email pass repass
        $input = $request->except('_token');
        //2.进行表单验证
        $manage_id = $input['data'];
        if (!empty($manage_id)) {
            $pos_a = strpos($manage_id, 'a');
            $pos_b = strpos($manage_id, 'b') != '' ? strpos($manage_id, 'b') : '';
            $manage = (!empty($pos_b)) ? substr($manage_id, $pos_a, $pos_b) : substr($manage_id, $pos_a);
            $stu_id = (!empty($pos_b)) ? substr($manage_id, $pos_b) : '';
            $manage = str_replace("a", "", $manage);
            $stu_id = str_replace("b", "", $stu_id);

            if (empty($stu_id) && !empty($manage)) {
                # code...
                $number_id = array_filter(explode(',', $manage));
                $number_id = implode(',', $number_id);
            }
            if (empty($manage) && !empty($stu_id)) {
                $number_id = array_filter(explode(',', $stu_id));
                $number_id = implode(',', $number_id);
            }
            if (!empty($manage) && !empty($stu_id)) {
                # code...
                $stu_id = array_filter(explode(',', $stu_id));
                $manage = array_filter(explode(',', $manage));
                $stu_id = implode(',', $stu_id);
                $manage = implode(',', $manage);
                $number_id = $stu_id . ',' . '' . ',' . $manage;
            }
        } else {

            return \redirect()->back()->with('errors', '成员不能为空！');

        }
        if ($input['file'] != "") {
            $file = implode('|', $input['file']);
        } else {
            $file = "";
        }

        //3.添加到数据库
        $time = Carbon::now()->toDateTimeString();
        $res = Task::create(['week_id' => $input['week_id'], 'term_id' => session()->get('term_id'), 'manage_id' => $number_id, 'title' => $input['title'], 'cont' => $input['bz'], 'file' => $file, 'time_check' => $input['time_check'], 'time_show' => $input['time_show'], 'time_up' => $input['time_up'], 'add_time' => $time, 'add_user' => session()->get('user')->user_name]);
//        return $res;
        //4.根据添加是否成功，给客户端返回一个json格式的反馈
        if ($res) {
            return \redirect()->back()->with('success', '恭喜，添加成功！');
        } else {
            return \redirect()->back()->with('errors', '添加失败！');
        }
    }

    public function Del($id)
    {
        $task = Task::find($id);
        $res = $task->delete();
        if ($res) {
            return \redirect()->back()->with('success', '恭喜，删除成功！');
        } else {
            return \redirect()->back()->with('errors', '删除失败！');
        }
    }

    public function tree()
    {


        $manage = Manage::select('id', 'username as title')->where('id', '!=', session()->get('user')->id)->get()->toArray();
        $stu = Stu::select('id', 'user_name as title')->get()->toArray();
//        $stu_data = [
//            'title' =>
//                '成员列表'
//            , 'id' => 'b'
//            , 'field' => ''
//            , 'children' => $stu
//        ];
//        $data = [$manage_data];
        return $manage;
    }

    public function upload(Request $request)
    {
        $file = $request->file('file');//获取文件，与layui中的js的配置 field:'file'。一致。
        $allowed_extensions = ["txt", "doc", "docx", "html", "sql", "xls", "ppt", "pdf"]; //多类型
        //判断文件是否是允许上传的文件类型
        if ($file->getClientOriginalExtension() && !in_array($file->getClientOriginalExtension(), $allowed_extensions)) {
            $data = [
                'status' => 0,//返回状态码，在js中用改状态判断是否上传成功。

            ];
            return json_encode($data);
        }

        //保存文件，新建路径，拷贝文件
        $path = date('Y/m/d/', time());
        $destinationPath = 'uploads/' . $path;
        is_dir($destinationPath) or mkdir($destinationPath, 0777, true);
        $extension = $file->getClientOriginalExtension();
        $fileName = Crypt::encrypt($file->getClientOriginalName()) . '.' . $extension;
        $file->move($destinationPath, $fileName);
        $data = [
            'status' => 1,//返回状态码，在js中用改状态判断是否上传成功。
            'msg' => $destinationPath . $fileName,//上传成功，返回服务器上文件名字
            'originalname' => $file->getClientOriginalName()//上传成功，返回上传原文件名字
        ];
        return json_encode($data);


    }
}
